package com.wonders.bigdata.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author xb
 * @descripton: txt转pdf
 * @date 2023/3/24
 */
public class Txt2PdfUtil {
    public static void main(String[] args) {
        String source = "D:/file/混沌剑神目录.txt";
        String target = "D:/file/混沌剑神目录.pdf";
        txt2Pdf(source, target);
    }

    public static void txt2Pdf(String txtPath, String pdfPath) {
        BufferedReader input = null;
        Document output = null;
        System.out.println("Convert text file to pdf");
        try {
            input = new BufferedReader (new FileReader(txtPath));
            output = new Document(PageSize.LETTER, 40, 40, 40, 40);
            PdfWriter.getInstance(output, new FileOutputStream(pdfPath));

            output.open();
            output.addAuthor("RealHowTo");
            output.addSubject(txtPath);
            output.addTitle(txtPath);

            String line = "";
            while(null != (line = input.readLine())) {
                System.out.println(line);
                Paragraph p = new Paragraph(line);
                p.setAlignment(Element.ALIGN_JUSTIFIED);
                output.add(p);
            }
            System.out.println("Done.");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (output != null) {
                output.close();
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
